﻿using System.IO;
using System.Threading;

namespace System
{
    /// <summary>
    /// 一个默认使用文件进行记录的日志器。
    /// </summary>
    public class FileLogger : LoggerBase
    {
        public override void LogInfo(string message)
        {
            string msg = string.Format(@"{0}|{1}|Inform|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg);
        }
        public override void LogWarn(string message)
        {
            string msg = string.Format(@"{0}|{1}|Warn|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Warn);
        }
        public override void LogDebug(string message)
        {
            string msg = string.Format(@"{0}|{1}|Debug|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Debug);
        }
        public override void LogTrace(string message)
        {
            string msg = string.Format(@"{0}|{1}|Trace|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Trace);
        }
        public override void LogSql(string message)
        {
            string msg = string.Format(@"{0}|{1}|Sql|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Sql);
        }
        public override void LogError(string title, Exception e)
        {
            var stackTrace = e.StackTrace;//需要记录完整的堆栈信息。
            e = e.GetBaseException();

            string errStr = ExceptionHelper.GetExceptionAllMsg(e);

            string msg = string.Format(@"{0}|{1}|Error|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId,
                title + Environment.NewLine + errStr);
            AppendAllText(msg, LogType.Error);
        }
        public override void LogError(string message)
        {
            string msg = string.Format(@"{0}|{1}|Error|{2}" + Environment.NewLine, DateTime.Now, Thread.CurrentThread.ManagedThreadId, message);
            AppendAllText(msg, LogType.Error);
        }
        private void AppendAllText(string contents, LogType logType = LogType.Info)
        {
            try
            {
                string t = "logs";
                string path = System.IO.Directory.GetCurrentDirectory() + "//" + t;
                string logfile = path + "/" + logType.ToString().ToLower() + "_" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                File.AppendAllText(logfile, contents);
            }
            catch (Exception)
            {

            }
        }
    }
}